﻿<%@ WebHandler Language="C#" Class="wxMiniProgramLogin" %>
using Models;
using System;
using System.Web;
using Newtonsoft.Json;
using System.Web.Configuration;
using WxPayAPI;
using System.Linq;
using Newtonsoft.Json.Linq;
using System.IO;

public class wxMiniProgramLogin : IHttpHandler {


    public static string APPID =WebConfigurationManager.AppSettings["APPID"];
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";

        StreamReader sr = new StreamReader(HttpContext.Current.Request.InputStream);
        string responseStr = sr.ReadToEnd();
       if (string.IsNullOrEmpty(responseStr.ToString()))
        {
            HttpContext.Current.Response.Write("parameter error");
            return;
        }

         JObject jo = (JObject)JsonConvert.DeserializeObject(responseStr);
            string order_sn = jo["order_sn"].ToString();
            string openid = jo["openid"].ToString();
   
        string postdata=Utils.PostInput(context);

        string authHeader = context.Request.Headers["token"];//Header中的token
        if (string.IsNullOrEmpty(authHeader))
        {
            HttpContext.Current.Response.Write("parameter error");
            return;
        }


        //  {"code":1,"msg":"获取预付款成功","time":"1610011032","data":{"pay_data":{"appId":"wx30bd16bac7283016","timeStamp":"1610011032","nonceStr":"GZm1G3metMjUwzBZ","package":"prepay_id=wx07171712541816923e08d7e85972110000","signType":"MD5","paySign":"9013CFEB768A0CA9AC7F0EEDD3280F15"},"pay_action":"miniapp"}}

        DateTime mytime = DateTime.Now.AddDays(1);
        long  TStamp= Utils.GetTimeStamp(mytime);


        Entities mydb = new Entities();
        S_Order Lt = mydb.S_Order.First(p => p.OOrderNumber == order_sn);
        var  myprice = _rky.getSumMoney(Lt.OrderID.ToString(), "SS", "1").ToString();// Lt.OLastPrice.ToString();
        var name = Lt.SPName;
        var mytp = "SP";
        var myOrderID = Lt.OrderID.ToString();

        WxPayData unifiedOrderResult = GetUnifiedOrderResult(Convert.ToInt32(Convert.ToDecimal(myprice) * 100), name, openid, mytp + DateTime.Now.ToString("yyyyMMddHHmmss") + myOrderID + "SS", myOrderID, mytp); //統一下單

        GetJsApiParameters(unifiedOrderResult);//获取H5调起JS API参数


        var data = new
        {    pay_action="miniapp",
            pay_data = new {
                appId =APPID,
                nonceStr=nonceStr,
                package=package,
                signType =signType,
                paySign =  paySign,
                timeStamp=timeStamp

            },
        };
        var  code = 1;
        var msg = "获取预付款成功";
        var time = DateTime.Now;



        context.Response.Write(JsonConvert.SerializeObject(new {code,msg,time,data}));

        HttpContext.Current.Response.End();
        //context.Response.Write("Hello World");


    }

    #region 支付相關
    protected string wxJsApiParam { get; set; }    //H5调起JS API参数
    protected string orderinfo;
    protected string money;
    protected int oid;

    protected WxPayData jsApiParam = new WxPayData();

    protected string appId, //公众号名称，由商户传入
                  timeStamp, //时间戳
                  nonceStr, //随机串
                  package, //扩展包
                  signType, //微信签名方式:1.sha1
                  paySign; //微信签名


    /**
    * 调用统一下单，获得下单结果
    * @return 统一下单结果
    * @失败时抛异常WxPayException
    */
    public WxPayData GetUnifiedOrderResult(int total_fee, string PName, string openid, string tradeno, string attach, string goods_tag)
    {
        //统一下单
        WxPayData data = new WxPayData();
        data.SetValue("body", PName);
        data.SetValue("attach", attach);
        data.SetValue("out_trade_no", tradeno);
        data.SetValue("total_fee", total_fee);
        data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
        data.SetValue("time_expire", DateTime.Now.AddMinutes(60).ToString("yyyyMMddHHmmss"));
        data.SetValue("goods_tag", goods_tag);
        data.SetValue("trade_type", "JSAPI");
        data.SetValue("openid", openid);

        WxPayData result = WxPayApi.UnifiedOrder(data);
        if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "")
        {
            WxPayAPI.Log.Error(this.GetType().ToString(), "UnifiedOrder response error!");
            throw new WxPayException("程序发生未知错误UnifiedOrder response error!");
        }
        //else
        //{
        //myOrderID = Session["myOrderID"].ToString();
        //int intmyOrderID = int.Parse(myOrderID);
        //Entities mydb = new Entities();
        //A_Pay Lt = mydb.A_Pay.First(p => p.PayID == intmyOrderID);
        //Lt.Paystatu = 1;
        //Lt.PayiIme = DateTime.Now;
        //mydb.SaveChanges();
        //}
        return result;
    }


    public void GetJsApiParameters(WxPayData unifiedOrderResult)
    {
        WxPayAPI.Log.Debug(this.GetType().ToString(), "JsApiPay::GetJsApiParam is processing...");

        jsApiParam = new WxPayData();
        jsApiParam.SetValue("appId", unifiedOrderResult.GetValue("appid"));
        jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp());
        jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr());
        jsApiParam.SetValue("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id"));
        jsApiParam.SetValue("signType", "MD5");
        jsApiParam.SetValue("paySign", jsApiParam.MakeSign());

        appId = "" + jsApiParam.GetValue("appId");
        timeStamp = "" + jsApiParam.GetValue("timeStamp");
        nonceStr = "" + jsApiParam.GetValue("nonceStr");
        package = "" + jsApiParam.GetValue("package");
        signType = "" + jsApiParam.GetValue("signType");
        paySign = "" + jsApiParam.GetValue("paySign");
    }
    #endregion





    public bool IsReusable {
        get {
            return false;
        }
    }

}